package middleware

import (
	"gitee.com/CrazyMage/lite-note/internal/controller/http/v1/response"
	"gitee.com/CrazyMage/lite-note/pkg/utils"
	"github.com/gin-gonic/gin"
)

func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 1. 从 Header 获取 Token
		tokenString := c.GetHeader("Authorization")
		if tokenString == "" {
			response.Error(c, 401, "未提供 Token")
			c.Abort()
			return
		}

		// 2. 解析 Token
		claims, err := utils.ParseToken(tokenString)
		if err != nil {
			response.Error(c, 401, "无效的 Token")
			c.Abort()
			return
		}

		// 3. 将用户信息存入 Context
		c.Set("user_id", claims.UserID)

		newCtx := utils.SetContextValue(c.Request.Context(), "user_id", claims.UserID)
		c.Request = c.Request.WithContext(newCtx)

		c.Next()
	}
}
